package cn.sytton.taffecloud.common.excel.aop;

import cn.sytton.taffecloud.common.db.model.PageParam;
import cn.sytton.taffecloud.common.excel.helper.ExportThread;
import cn.sytton.taffecloud.common.excel.helper.PageToExcel;
import com.github.pagehelper.PageInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Excel导出切面类，实现结果的自动转换
 *
 * @author skyrock
 */
@Aspect
@Component
public class ExportExcelAspectJ {

    @Pointcut("@annotation(cn.sytton.taffecloud.common.excel.annotation.ExportExcel)")
    private void aspectJMethod(){}//定义一个切入点

    @Before("aspectJMethod()")
    public void before(JoinPoint joinPoint) {
        if (joinPoint.getArgs() != null) {
            for(Object arg : joinPoint.getArgs()) {
                if (arg instanceof PageParam) {
                    Map<String, Object> export = ((PageParam) arg).getExport();
                    if (export != null) {
                        // 被拦截方法中存在 PageParam 参数，并且存在export导出的参数值
                        ExportThread.setData(((PageParam) arg).getExport());
                    }
                }
                break;
            }
        }
    }

    @AfterReturning(returning = "value",pointcut = "aspectJMethod()")
    public void afterReturning(JoinPoint joinPoint, Object value){
        Map<String, Object> params = ExportThread.getData();
        if (params != null && value instanceof PageInfo) {
            PageToExcel.export(params, (PageInfo<?>) value);
        }
    }
}
